package com.dht.xiao.jianye.command.base.serialport;

import android.util.ArrayMap;

import com.dht.xiao.jianye.command.base.serialport.bean.InitSerialPortBean;
import com.dht.xiao.jianye.command.base.serialport.callback.BaseDataCallback;
import com.dht.xiao.jianye.command.base.serialport.callback.SendResultCallback;
import com.dht.xiao.jianye.command.base.serialport.callback.SerialPortCallback;

import java.util.Map;


/**
 * @author :      fangbingran
 * @aescription : todo(这里用一句话描述这个类的作用)
 * @date :        2019/06/06  10:13
 */
public class SerialPortServiceProxy {
    private static class InstanceSerialPortServiceProxy {
        private static final SerialPortServiceProxy INSTANCE = new SerialPortServiceProxy();
    }

    public static SerialPortServiceProxy get() {
        return InstanceSerialPortServiceProxy.INSTANCE;
    }

    private Map<String, SerialPortService> map = new ArrayMap<>();

    public SerialPortServiceProxy add(String key, SerialPortService serialPortService) {
        map.put(key, serialPortService);
        return this;
    }

    public SerialPortServiceProxy add(String key, InitSerialPortBean initSerialPortBean, BaseDataCallback baseDataCallback, SerialPortCallback serialPortCallback) {
        return add(key, new SerialPortService(initSerialPortBean, baseDataCallback, serialPortCallback));
    }

    public void send(String key, CmdPack cmdPack, SendResultCallback sendResultCallback) {
        if (map.containsKey(key)) {
            SerialPortService serialPortService = map.get(key);
            if (serialPortService != null) {
                serialPortService.send(cmdPack, sendResultCallback);
            }
        }
    }

    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        for (SerialPortService serialPortService : map.values()) {
            if (serialPortService != null) {
                serialPortService.closeSerialPort();
            }
        }
        map.clear();
    }
}
